package com.xspace.android.xafview.zxing.file;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.ReaderException;
import com.google.zxing.common.HybridBinarizer;

import java.util.Hashtable;
import java.util.Vector;

public class ZxingFile {
	public Bitmap decodePath(String imgPath) {
		Bitmap bm = BitmapFactory.decodeFile(imgPath);
		return bm;
	}
	public Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }
	public String deCode(Bitmap bitmap) {
		if (bitmap == null) {
			Log.i("deCode", "-----------------------null");
			return "null";
		}

		Hashtable<DecodeHintType, Object> hints = null;
		initHints(hints, null, "UTF8");// 注意不要写成UTF-8，因为它里面自己包装的是UTF8
		MultiFormatReader multiFormatReader = new MultiFormatReader();
		multiFormatReader.setHints(hints);

		LuminanceSource source = new BitmapLuance(bitmap);

		BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(source));

		try {
			return multiFormatReader.decodeWithState(bit).getText();

		} catch (ReaderException re) {
			// continue
		} finally {
			multiFormatReader.reset();
		}
		return null;
	}

	public void initHints(Hashtable<DecodeHintType, Object> hints,
			Vector<BarcodeFormat> decodeFormats, String CODE_STYLE) {
		hints = new Hashtable<DecodeHintType, Object>(2);
		if (decodeFormats == null || decodeFormats.isEmpty()) {
			decodeFormats = new Vector<BarcodeFormat>();
			decodeFormats.addAll(MyDecodeFormatManager.ONE_D_FORMATS);
			decodeFormats.addAll(MyDecodeFormatManager.QR_CODE_FORMATS);
			decodeFormats.addAll(MyDecodeFormatManager.DATA_MATRIX_FORMATS);
		}

		hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
		if (CODE_STYLE != null) {
			Log.i("initHints", "-----------------------4");
			// 下面这句不加编码方式更方便，让它自己查找。当然效率可能要低一些，但适用性更广
			// hints.put(DecodeHintType.CHARACTER_SET, CODE_STYLE);
		}

	}

}
